package org.btik.light.tool;

import java.io.ByteArrayOutputStream;

public class ByteArrayBuffer extends ByteArrayOutputStream {
    private static final int EOF = -1;

    /**
     * 取走数据后滑动到0位
     */
    private synchronized void slide(int len) {
        count -= len;
        System.arraycopy(buf, len, buf, 0, count);
    }

    public synchronized int read() {
        if (count < 1) {
            return EOF;
        }
        byte b = buf[0];
        slide(1);
        return b;
    }

    public synchronized int read(byte[] bytes) {
        int length = bytes.length;
        if (length == 0) {
            return length;
        }
        if (count < 1) {
            return EOF;
        }
        int len = Math.min(length, count);
        System.arraycopy(buf, 0, bytes, 0, len);
        slide(len);
        return len;
    }
}
